var util = require('utils/util');
var wxApi = require('utils/wxApi');
var wxRequest = require('utils/wxRequest');
// var config = require('utils/config');
import config from 'utils/config'



var obj = null;
var url_https_self ="";


function version(){
    console.log('envVersion', __wxConfig.envVersion);
    let version = __wxConfig.envVersion;
    switch (version)
    {
      case 'develop':
        return 'https://app.dkcake.com/test';
        break;
      case 'trial':
        return 'https://app.dkcake.com/test';
        break;
      case 'release':
        return 'https://app.dkcake.com';
        break;
      default:
        return 'http://localhost:6241';
    }
  }
  var url_https_self = version();
// url_https_self = 'https://app.dkcake.com';
  var url_https = url_https_self;//'https://app.dkcake.com';
// var url_https = url_https_self;
//  util.alert(url_https_self);

App({
  onLaunch: function () {
    if (wx.canIUse("getUpdateManager")) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function(res) {
       
        // 请求完新版本信息的回调
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function() {
            wx.showModal({
              title: "更新提示",
              content: "新版本已经准备好，请重新启动",
			        showCancel: false,
              success(res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate();
                }
              }
            });
          });
          updateManager.onUpdateFailed(function() {
            // 新的版本下载失败
            wx.showModal({
              title: "已经有新版本了哟~",
              content: "新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~"
            });
          });
        }
      });
		  
    } else {
      wx.showModal({
        title: "提示",
        content:
          "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
      });
    }
    
  },
  globalData: {
    appid: 'wx1c237d099d8cad5c',
    url_local: url_https_self  ,
    url_https: url_https ,
    dhkb_url:"",
    user: obj,
    mheight:1334,
    mweight:750,
    defaultPageSize:20,
    share:{title:"每一步，都算数",path:"pages/index/index",imageUrl:"https://app.dkcake.com/images/share.jpg"},
    tmp:{},
    isnew:0
  }
  ,getShare:function(){
      var obj = this.globalData.share;
      var pages = getCurrentPages();
      pages = pages[pages.length - 1];
      var route = pages.route;
      obj.path =  route; //.substr(5);
      var arrp=[];
      if(pages.hasOwnProperty("options")){
          for(var x in pages.options){
              arrp.push(x+"="+pages.options[x]);
          }
      }
      if(arrp.length >0){
          obj.path = obj.path +"?"+arrp.join("&");
      }

      //if(pages.data.hasOwnProperty("_spath")){
      //    obj.path =pages.data._spath;
      //}

      //if(pages.data.hasOwnProperty("_stitle")){
      //    obj.title =pages.data._stitle;
      //}

      //if(pages.data.hasOwnProperty("_sdesc")){
      //      obj.title =pages.data._sdesc;
      //}

      if(pages.data.hasOwnProperty("_simg")){
          obj.imageUrl =pages.data._simg;
      }
      obj.success=function(){
        //util.alert("成功")
      }

      //obj.imageUrl="https://app.dkcake.com/images/share.png";
      return obj;
  }
  ,getUserInfo:function(cb){
    var that = this;
    
    return new Promise((resolve, reject) => {

		if (false) {
            console.log('99.已存在');
            resolve(that.globalData.user);
        }else{
            console.log('0.开始登陆');
        
        if(cb===false){
          var dd = wx.getStorageSync('data');
          if(!util.judge.isNull(dd)){
              that.globalData.user=dd.user;
              that.globalData.isnew= dd.isnew;
          }else{
              that.globalData.user=null;
          }
          resolve(that.globalData.user);
          throw util.stop();
        }
            
        var getSetting = wxApi.wxgetSetting();
        getSetting().then(res => {
				var u = res.authSetting['scope.userInfo'];
				var l = res.authSetting['scope.userLocation'];
        var r = res.authSetting['scope.werun'];//|| r== false || util.judge.isNull(r)
        
				if( u== false || util.judge.isNull(u) || l== false || util.judge.isNull(l)  ){
 
          
				    if(util.judge.isNull(u) || u == false){
				        u="u";
				        wx.redirectTo({
				            url: '../index/sq?p=1&url='+url_https
				        });
				        throw util.stop();
				    }
				    //|| util.judge.isNull(r) || r == false
				    if(util.judge.isNull(l) || l == false  ){
				        l="l";
				    }
				   
            wx.redirectTo({
                url: '../index/sq?url='+url_https
            });
            throw util.stop();
				}

				//this.globalData.user=null;
				var dd = wx.getStorageSync('data');
				if(!util.judge.isNull(dd)){
				    that.globalData.user=dd.user;
				    that.globalData.isnew= dd.isnew;
				    // wx.setStorageSync('data',null);
				}else{
				    that.globalData.user=null;
				}

				wx.checkSession({
				    success:() => {
				        if (that.globalData.user && that.globalData.user != null && typeof that.globalData.user == "object" && that.globalData.user.hasOwnProperty("uid") && that.globalData.user.uid > 0) {
				            console.log('99.已存在');
				            resolve(that.globalData.user);
				           
				        }else{
				            wx.clearStorageSync();//清除所有缓存
				            wx.redirectTo({
				                url: '../index/sq?p=1&url='+url_https
				            });
				            
				        }
				    },
				    fail:() => {
				        wx.clearStorageSync();//清除所有缓存
				        wx.redirectTo({
				            url: '../index/sq?p=1&url='+url_https
				        });
				        
				    }
				});
				
      }) 
			.catch(res => {
        console.log('7.err-'+res);
        wx.clearStorageSync();//清除所有缓存
			})
			.finally(function (res) {
			  // wx.hideToast();
			  console.log('app.getuser.finally~')
			});
		}
     
    });
  }

})
//很重要
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};